package com.ad.aidai.base;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.ad.aidai.common.listener.OnActivityBackPressedListener;
import com.ad.aidai.common.ADFragmentManager;
import com.umeng.analytics.MobclickAgent;

import butterknife.ButterKnife;
import rx.Subscription;
import rx.subscriptions.CompositeSubscription;

/**
 * BaseFragment抽象类
 * <p>
 * Created by Yusxon on 16/11/26.
 */

public abstract class BaseFragment extends Fragment implements OnActivityBackPressedListener {

    protected Context mContext = null;
    protected Activity mActivity = null;
    protected View mView = null;

    private CompositeSubscription mSubscriptions;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState) {

        initLayout(inflater, container, savedInstanceState);
        mContext = getContext();
        mActivity = getActivity();
        ButterKnife.bind(this, mView);
        initData();
        subscribeEvents();
        initView();

        return mView;
    }

    protected abstract void initLayout(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle
            savedInstanceState);

    protected abstract void initView();

    protected abstract void initData();

    protected void subscribeEvents() {
    }

    protected void addSubscription(Subscription subscription) {
        if (subscription == null)
            return;
        if (mSubscriptions == null) {
            mSubscriptions = new CompositeSubscription();
        }
        mSubscriptions.add(subscription);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mSubscriptions != null) {
            mSubscriptions.clear();
        }
    }

    public void toast(String message) {
        Toast.makeText(mContext, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }

    @Override
    public void onStart() {
        ADFragmentManager.addListener(this);
        ADFragmentManager.addTag(this.getClass().getSimpleName());
        super.onStart();
    }

    @Override
    public void onDestroy() {
        ADFragmentManager.removeListener();
        ADFragmentManager.removeTag();
        super.onDestroy();
    }
}
